<template>
  <div class="diary-detail-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <button class="back-btn" @click="goBack">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2"/>
            </svg>
            返回
          </button>
        </div>

        <div class="header-actions">
          <button class="action-btn edit" @click="editDiary">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="currentColor" stroke-width="2"/>
              <path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2"/>
            </svg>
            编辑
          </button>

          <button class="action-btn share" @click="shareDiary">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M4 12v8a2 2 0 002 2h12a2 2 0 002-2v-8M16 6l-4-4-4 4M12 2v13" stroke="currentColor" stroke-width="2"/>
            </svg>
            分享
          </button>

          <div class="more-actions">
            <button class="action-btn more" @click="showMoreMenu = !showMoreMenu">
              <svg fill="none" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
                <circle cx="19" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
                <circle cx="5" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
              </svg>
            </button>

            <div v-if="showMoreMenu" class="more-menu" @click.stop>
              <button class="menu-item" @click="exportDiary">
                <svg fill="none" viewBox="0 0 24 24">
                  <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" stroke="currentColor" stroke-width="2"/>
                </svg>
                导出
              </button>
              <button class="menu-item danger" @click="deleteDiary">
                <svg fill="none" viewBox="0 0 24 24">
                  <polyline points="3,6 5,6 21,6" stroke="currentColor" stroke-width="2"/>
                  <path d="M19,6v14a2,2 0 0,1 -2,2H7a2,2 0 0,1 -2,-2V6m3,0V4a2,2 0 0,1 2,-2h4a2,2 0 0,1 2,2v2" stroke="currentColor" stroke-width="2"/>
                </svg>
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div v-if="diary" class="main-content">
      <div class="content-grid">
        <!-- 日记文章 -->
        <article class="diary-article">
          <div class="article-container">
            <!-- 文章头部 -->
            <header class="article-header">
              <div class="header-meta">
                <div class="meta-item date">
                  <svg fill="none" viewBox="0 0 24 24">
                    <path d="M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V6a2 2 0 012-2z" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  {{ formatFullDate(diary.date) }}
                </div>
                <div class="meta-item time">
                  <svg fill="none" viewBox="0 0 24 24">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                    <polyline points="12,6 12,12 16,14" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  {{ formatTime(diary.date) }}
                </div>
                <div :class="diary.mood" class="meta-item mood">
                  <span class="mood-emoji">{{ getMoodEmoji(diary.mood) }}</span>
                  <span class="mood-text">{{ getMoodLabel(diary.mood) }}</span>
                </div>
              </div>

              <h1 class="article-title">{{ diary.title }}</h1>
            </header>

            <!-- 文章内容 -->
            <div class="article-body">
              <div class="diary-content" v-html="formattedContent"></div>

              <!-- 附件图片 -->
              <div v-if="diary.photos && diary.photos.length > 0" class="diary-attachments">
                <h3 class="attachments-title">
                  <svg fill="none" viewBox="0 0 24 24">
                    <path d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" stroke="currentColor" stroke-width="2"/>
                </svg>
                照片 ({{ diary.photos.length }})
                </h3>
                <div class="photos-gallery">
                  <div
                    v-for="(photo, index) in diary.photos"
                    :key="index"
                    class="photo-item"
                    @click="openPhotoViewer(index)"
                  >
                    <img :alt="photo.name" :src="photo.thumbnail" />
                    <div class="photo-overlay">
                      <svg fill="none" viewBox="0 0 24 24">
                        <path d="M15 3h6v6M14 10l6.1-6.1M9 21H3v-6M10 14l-6.1 6.1" stroke="currentColor" stroke-width="2"/>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 标签 -->
              <div v-if="diary.tags && diary.tags.length > 0" class="diary-tags">
                <h3 class="tags-title">
                  <svg fill="none" viewBox="0 0 24 24">
                    <path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z" stroke="currentColor" stroke-width="2"/>
                    <line stroke="currentColor" stroke-width="2" x1="7" x2="7.01" y1="7" y2="7"/>
                  </svg>
                  标签
                </h3>
                <div class="tags-container">
                  <button
                    v-for="tag in diary.tags"
                    :key="tag"
                    class="tag-item"
                    @click="searchByTag(tag)"
                  >
                    {{ tag }}
                  </button>
                </div>
              </div>
            </div>

            <!-- 文章底部 -->
            <footer class="article-footer">
              <div class="reading-info">
                <div class="info-item">
                  <svg fill="none" viewBox="0 0 24 24">
                    <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" stroke="currentColor" stroke-width="2"/>
                    <polyline points="14,2 14,8 20,8" stroke="currentColor" stroke-width="2"/>
                    <line stroke="currentColor" stroke-width="2" x1="16" x2="8" y1="13" y2="13"/>
                    <line stroke="currentColor" stroke-width="2" x1="16" x2="8" y1="17" y2="17"/>
                    <polyline points="10,9 9,9 8,9" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  <span>{{ wordCount }} 字</span>
                </div>
                <div class="info-item">
                  <svg fill="none" viewBox="0 0 24 24">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                    <polyline points="12,6 12,12 16,14" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  <span>阅读约 {{ readingTime }} 分钟</span>
                </div>
                <div class="info-item">
                  <svg fill="none" viewBox="0 0 24 24">
                    <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" stroke="currentColor" stroke-width="2"/>
                    <circle cx="12" cy="7" r="4" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  <span>{{ diary.author || '我' }}</span>
                </div>
              </div>

              <div class="article-actions">
                <LikeButton
                  :initial-count="likeCount"
                  :initial-liked="isLiked"
                  :target-id="parseInt(diary.id)"
                  size="medium"
                  target-type="diary"
                  variant="outline"
                  @like-changed="handleLikeChanged"
                />

                <ShareButton
                  :description="diary.content.substring(0, 100) + '...'"
                  :share-url="`${window.location.origin}/diary/${diary.id}`"
                  :show-text="false"
                  :title="diary.title"
                  size="medium"
                  variant="outline"
                  @share="handleShare"
                />

                <button :class="{ active: isBookmarked }" class="footer-action bookmark" @click="toggleBookmark">
                  <svg fill="none" viewBox="0 0 24 24">
                    <path d="M19 21l-7-5-7 5V5a2 2 0 012-2h10a2 2 0 012 2z" stroke="currentColor" stroke-width="2"/>
                  </svg>
                </button>
              </div>
            </footer>
          </div>
        </article>

        <!-- 侧边栏 -->
        <aside class="diary-sidebar">
          <!-- 导航信息 -->
          <div class="navigation-card">
            <h3 class="card-title">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M9 11H5a2 2 0 00-2 2v7a2 2 0 002 2h14a2 2 0 002-2v-7a2 2 0 00-2-2h-4M9 11V9a2 2 0 112 0v2m-6 0h6m-6 0H3" stroke="currentColor" stroke-width="2"/>
              </svg>
              导航
            </h3>
            <div class="nav-links">
              <router-link :class="{ disabled: !prevDiaryId }" :to="prevDiaryId ? `/diary/${prevDiaryId}` : '#'" class="nav-item prev">
                <svg fill="none" viewBox="0 0 24 24">
                  <polyline points="15,18 9,12 15,6" stroke="currentColor" stroke-width="2"/>
                </svg>
                <span>上一篇</span>
              </router-link>
              <router-link :class="{ disabled: !nextDiaryId }" :to="nextDiaryId ? `/diary/${nextDiaryId}` : '#'" class="nav-item next">
                <span>下一篇</span>
                <svg fill="none" viewBox="0 0 24 24">
                  <polyline points="9,18 15,12 9,6" stroke="currentColor" stroke-width="2"/>
                </svg>
              </router-link>
            </div>
          </div>

          <!-- 相关日记 -->
          <div class="related-card">
            <h3 class="card-title">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" stroke="currentColor" stroke-width="2"/>
              </svg>
              相关日记
            </h3>
            <div class="related-list">
              <div
                v-for="related in relatedDiaries"
                :key="related.id"
                class="related-item"
                @click="openDiary(related.id)"
              >
                <div class="related-content">
                  <h4 class="related-title">{{ related.title }}</h4>
                  <div class="related-meta">
                    <span class="related-date">{{ formatDate(related.date) }}</span>
                    <span class="related-mood">{{ getMoodEmoji(related.mood) }}</span>
                  </div>
                </div>
                <svg class="related-arrow" fill="none" viewBox="0 0 24 24">
                  <polyline points="9,18 15,12 9,6" stroke="currentColor" stroke-width="2"/>
                </svg>
              </div>
            </div>
          </div>

          <!-- 心情统计 -->
          <div class="mood-stats-card">
            <h3 class="card-title">
              <svg fill="none" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                <path d="M8 14s1.5 2 4 2 4-2 4-2" stroke="currentColor" stroke-width="2"/>
                <line stroke="currentColor" stroke-width="2" x1="9" x2="9.01" y1="9" y2="9"/>
                <line stroke="currentColor" stroke-width="2" x1="15" x2="15.01" y1="9" y2="9"/>
              </svg>
              最近心情
            </h3>
            <div class="mood-chart">
              <div
                v-for="mood in recentMoods"
                :key="mood.type"
                class="mood-row"
              >
                <div class="mood-info">
                  <span class="mood-emoji">{{ getMoodEmoji(mood.type) }}</span>
                  <span class="mood-label">{{ getMoodLabel(mood.type) }}</span>
                </div>
                <div class="mood-progress">
                  <div
                    :class="mood.type"
                    :style="{ width: mood.percentage + '%' }"
                    class="mood-bar"
                  ></div>
                </div>
                <span class="mood-count">{{ mood.count }}</span>
              </div>
            </div>
          </div>
        </aside>
      </div>

      <!-- 评论系统 -->
      <div class="comments-section">
        <CommentSystem
          :allow-comment="true"
          :emoji-enabled="true"
          :image-enabled="false"
          :max-length="500"
          :mention-enabled="true"
          :target-id="parseInt(diary.id)"
          target-type="diary"
          @comment-added="handleCommentAdded"
          @comment-updated="handleCommentUpdated"
          @comment-deleted="handleCommentDeleted"
        />
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading-state">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <p class="loading-text">正在加载日记...</p>
      </div>
    </div>

    <!-- 照片查看器 -->
    <div v-if="showPhotoViewer" class="photo-viewer-overlay" @click="closePhotoViewer">
      <div class="photo-viewer" @click.stop>
        <div class="viewer-header">
          <div class="viewer-info">
            <span class="photo-counter">{{ currentPhotoIndex + 1 }} / {{ diary?.photos?.length }}</span>
            <span class="photo-name">{{ currentPhoto?.name }}</span>
          </div>
          <button class="viewer-close" @click="closePhotoViewer">
            <svg fill="none" viewBox="0 0 24 24">
              <line stroke="currentColor" stroke-width="2" x1="18" x2="6" y1="6" y2="18"/>
              <line stroke="currentColor" stroke-width="2" x1="6" x2="18" y1="6" y2="18"/>
            </svg>
          </button>
        </div>

        <div class="viewer-content">
          <button
            :disabled="currentPhotoIndex === 0"
            class="viewer-nav prev"
            @click="previousPhoto"
          >
            <svg fill="none" viewBox="0 0 24 24">
              <polyline points="15,18 9,12 15,6" stroke="currentColor" stroke-width="2"/>
            </svg>
          </button>

          <img :alt="currentPhoto?.name" :src="currentPhoto?.url" class="viewer-image" />

          <button
            :disabled="currentPhotoIndex === (diary?.photos?.length || 1) - 1"
            class="viewer-nav next"
            @click="nextPhoto"
          >
            <svg fill="none" viewBox="0 0 24 24">
              <polyline points="9,18 15,12 9,6" stroke="currentColor" stroke-width="2"/>
            </svg>
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteDialog" class="modal-overlay" @click="showDeleteDialog = false">
      <div class="modal-dialog" @click.stop>
        <div class="modal-header">
          <h3>删除日记</h3>
        </div>
        <div class="modal-body">
          <p>确定要删除这篇日记吗？删除后无法恢复。</p>
        </div>
        <div class="modal-footer">
          <button class="modal-btn secondary" @click="showDeleteDialog = false">取消</button>
          <button class="modal-btn danger" @click="confirmDelete">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Notify } from '@opentiny/vue'
import LikeButton from '@/components/social/LikeButton.vue'
import ShareButton from '@/components/social/ShareButton.vue'
import CommentSystem from '@/components/social/CommentSystem.vue'

const route = useRoute()
const router = useRouter()

interface Diary {
  id: string
  title: string
  content: string
  date: Date
  mood: 'happy' | 'sad' | 'excited' | 'calm' | 'thoughtful' | 'tired' | 'angry'
  tags: string[]
  author?: string
  photos?: Array<{
    name: string
    thumbnail: string
    url: string
  }>
}

interface RelatedDiary {
  id: string
  title: string
  date: Date
  mood: string
}

// 响应式数据
const diary = ref<Diary | null>(null)
const relatedDiaries = ref<RelatedDiary[]>([])
const showPhotoViewer = ref(false)
const showMoreMenu = ref(false)
const showDeleteDialog = ref(false)
const currentPhotoIndex = ref(0)
const isLiked = ref(false)
const isBookmarked = ref(false)
const likeCount = ref(12)

// 导航相关
const prevDiaryId = ref<string | null>('4')
const nextDiaryId = ref<string | null>('2')

// 心情统计数据
const recentMoods = ref([
  { type: 'happy', count: 8, percentage: 40 },
  { type: 'excited', count: 5, percentage: 25 },
  { type: 'calm', count: 4, percentage: 20 },
  { type: 'thoughtful', count: 2, percentage: 10 },
  { type: 'sad', count: 1, percentage: 5 }
])

// 计算属性
const wordCount = computed(() => {
  if (!diary.value?.content) return 0
  return diary.value.content.replace(/<[^>]*>/g, '').length
})

const readingTime = computed(() => {
  const wordsPerMinute = 200
  return Math.ceil(wordCount.value / wordsPerMinute) || 1
})

const formattedContent = computed(() => {
  if (!diary.value?.content) return ''
  return diary.value.content.replace(/\n/g, '<br>')
})

const currentPhoto = computed(() => {
  if (!diary.value?.photos || currentPhotoIndex.value >= diary.value.photos.length) {
    return null
  }
  return diary.value.photos[currentPhotoIndex.value]
})

// 页面初始化
onMounted(() => {
  loadDiary()
  loadRelatedDiaries()

  // 点击其他地方关闭更多菜单
  document.addEventListener('click', () => {
    showMoreMenu.value = false
  })
})

// 数据加载
const loadDiary = async () => {
  const diaryId = route.params.id as string

  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    diary.value = {
      id: diaryId,
      title: '美好的周末时光',
      content: `今天和家人一起去公园野餐，孩子们玩得很开心，感受到了满满的幸福。天气格外晴朗，微风轻抚，是个完美的野餐日。

我们带了很多好吃的，在草地上铺开野餐垫，一家人其乐融融地享受着这难得的悠闲时光。孩子们在草地上奔跑嬉戏，笑声回荡在整个公园里。

我们还在公园的湖边喂了鸭子，孩子们特别兴奋。看着他们天真无邪的笑容，我深深地被这份纯真所感动。

夕阳西下的时候，我们一家人坐在湖边的凉亭里，享受着这美好的时光。微风轻抚过脸庞，带着花香和青草的味道，这一刻的宁静和美好，让我觉得生活就应该这样简单而充实。

感恩能有这样平凡而美好的一天，这些看似普通的时光，其实是人生中最珍贵的宝藏。`,
      date: new Date('2024-01-20T15:30:00'),
      mood: 'happy',
      author: '我',
      tags: ['家庭', '野餐', '周末', '幸福', '感恩'],
      photos: [
        {
          name: '公园野餐.jpg',
          thumbnail: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
          url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop'
        },
        {
          name: '家人合影.jpg',
          thumbnail: 'https://images.unsplash.com/photo-1551632811-561732d1e306?w=400&h=300&fit=crop',
          url: 'https://images.unsplash.com/photo-1551632811-561732d1e306?w=800&h=600&fit=crop'
        },
        {
          name: '湖边夕阳.jpg',
          thumbnail: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
          url: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop'
        }
      ]
    }
  } catch (error) {
    console.error('加载日记失败:', error)
    Notify({
      type: 'error',
      message: '加载日记失败，请重试',
      position: 'top-right'
    })
  }
}

const loadRelatedDiaries = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))

    relatedDiaries.value = [
      {
        id: '2',
        title: '新年新计划',
        date: new Date('2024-01-01T09:00:00'),
        mood: 'thoughtful'
      },
      {
        id: '3',
        title: '项目完成的成就感',
        date: new Date('2024-01-18T18:20:00'),
        mood: 'excited'
      },
      {
        id: '4',
        title: '雨天的思考',
        date: new Date('2024-01-15T14:10:00'),
        mood: 'calm'
      }
    ]
  } catch (error) {
    console.error('加载相关日记失败:', error)
  }
}

// 格式化函数
const formatDate = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) return '今天'
  if (days === 1) return '昨天'
  if (days < 7) return `${days} 天前`

  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const formatFullDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
}

const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getMoodEmoji = (mood: string) => {
  switch (mood) {
    case 'happy': return '😊'
    case 'excited': return '😆'
    case 'calm': return '😌'
    case 'thoughtful': return '🤔'
    case 'sad': return '😢'
    case 'tired': return '😴'
    case 'angry': return '😠'
    default: return '📝'
  }
}

const getMoodLabel = (mood: string) => {
  switch (mood) {
    case 'happy': return '开心'
    case 'excited': return '兴奋'
    case 'calm': return '平静'
    case 'thoughtful': return '沉思'
    case 'sad': return '难过'
    case 'tired': return '疲惫'
    case 'angry': return '生气'
    default: return '未知'
  }
}

// 事件处理
const goBack = () => {
  router.back()
}

const editDiary = () => {
  router.push(`/diary/write?id=${diary.value?.id}`)
}

const shareDiary = () => {
  console.log('分享日记:', diary.value?.title)
  Notify({
    type: 'success',
    message: '分享链接已复制到剪贴板',
    position: 'top-right'
  })
}

const exportDiary = () => {
  console.log('导出日记:', diary.value?.title)
  Notify({
    type: 'info',
    message: '导出功能开发中...',
    position: 'top-right'
  })
}

const deleteDiary = () => {
  showMoreMenu.value = false
  showDeleteDialog.value = true
}

const confirmDelete = async () => {
  if (!diary.value) return

  try {
    // 模拟删除API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    Notify({
      type: 'success',
      message: '日记已删除',
      position: 'top-right'
    })

    router.push('/diary')
  } catch (error) {
    console.error('删除失败:', error)
    Notify({
      type: 'error',
      message: '删除失败，请重试',
      position: 'top-right'
    })
  } finally {
    showDeleteDialog.value = false
  }
}

const searchByTag = (tag: string) => {
  router.push(`/diary?search=${encodeURIComponent(tag)}`)
}

const openDiary = (diaryId: string) => {
  router.push(`/diary/${diaryId}`)
}

// 使用新的社交组件事件处理
const handleLikeChanged = (data: { liked: boolean; count: number }) => {
  isLiked.value = data.liked
  likeCount.value = data.count
  console.log('Diary like changed:', data)
}

const handleShare = (type: string, options?: any) => {
  console.log('Diary shared:', type, options)
  Notify({
    type: 'success',
    message: `已通过${type}分享日记`,
    position: 'top-right'
  })
}

const handleCommentAdded = (comment: any) => {
  console.log('Comment added to diary:', comment)
  Notify({
    type: 'success',
    message: '评论已发表',
    position: 'top-right'
  })
}

const handleCommentUpdated = (comment: any) => {
  console.log('Comment updated:', comment)
  Notify({
    type: 'success',
    message: '评论已更新',
    position: 'top-right'
  })
}

const handleCommentDeleted = (commentId: number) => {
  console.log('Comment deleted:', commentId)
  Notify({
    type: 'success',
    message: '评论已删除',
    position: 'top-right'
  })
}

const toggleBookmark = () => {
  isBookmarked.value = !isBookmarked.value
  Notify({
    type: 'success',
    message: isBookmarked.value ? '已收藏' : '已取消收藏',
    position: 'top-right'
  })
}

// 照片查看器
const openPhotoViewer = (index: number) => {
  currentPhotoIndex.value = index
  showPhotoViewer.value = true
  document.body.style.overflow = 'hidden'
}

const closePhotoViewer = () => {
  showPhotoViewer.value = false
  document.body.style.overflow = ''
}

const previousPhoto = () => {
  if (currentPhotoIndex.value > 0) {
    currentPhotoIndex.value--
  }
}

const nextPhoto = () => {
  if (diary.value?.photos && currentPhotoIndex.value < diary.value.photos.length - 1) {
    currentPhotoIndex.value++
  }
}
</script>

<style lang="scss" scoped>
.diary-detail-view {
  background: #f8fafc;
  min-height: 100vh;
  padding: 2rem 1rem;

  .page-header {
    max-width: 1200px;
    margin: 0 auto 2rem;

    .header-content {
      background: white;
      padding: 1.5rem 2rem;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        align-items: center;
        gap: 1.5rem;

        .back-btn {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.5rem 1rem;
          background: #f3f4f6;
          color: #6b7280;
          border: none;
          border-radius: 8px;
          cursor: pointer;
          transition: all 0.2s ease;

          &:hover {
            background: #e5e7eb;
            color: #374151;
          }

          svg {
            width: 16px;
            height: 16px;
          }
        }
      }

      .header-actions {
        display: flex;
        align-items: center;
        gap: 0.75rem;

        .action-btn {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          padding: 0.5rem 1rem;
          border-radius: 6px;
          border: none;
          cursor: pointer;
          transition: all 0.2s ease;
          font-size: 0.9rem;
          font-weight: 500;

          svg {
            width: 16px;
            height: 16px;
          }

          &.edit {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;

            &:hover {
              background: rgba(59, 130, 246, 0.2);
            }
          }

          &.share {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;

            &:hover {
              background: rgba(16, 185, 129, 0.2);
            }
          }
        }

        .more-actions {
          position: relative;

          .action-btn.more {
            background: rgba(107, 114, 128, 0.1);
            color: #6b7280;

            &:hover {
              background: rgba(107, 114, 128, 0.2);
            }
          }

          .more-menu {
            position: absolute;
            top: 100%;
            right: 0;
            margin-top: 0.5rem;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            min-width: 120px;
            z-index: 10;

            .menu-item {
              display: flex;
              align-items: center;
              gap: 0.5rem;
              width: 100%;
              padding: 0.75rem 1rem;
              background: none;
              border: none;
              text-align: left;
              cursor: pointer;
              transition: background 0.2s ease;
              font-size: 0.9rem;

              &:hover {
                background: #f3f4f6;
              }

              &.danger {
                color: #ef4444;

                &:hover {
                  background: rgba(239, 68, 68, 0.1);
                }
              }

              svg {
                width: 14px;
                height: 14px;
              }
            }
          }
        }
      }
    }
  }

  .main-content {
    max-width: 1200px;
    margin: 0 auto;

    .content-grid {
      display: grid;
      grid-template-columns: 1fr 320px;
      gap: 2rem;

      @media (max-width: 1024px) {
        grid-template-columns: 1fr;
      }
    }
  }

  .diary-article {
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .article-container {
      padding: 2rem;

      .article-header {
        margin-bottom: 2rem;

        .header-meta {
          display: flex;
          align-items: center;
          gap: 1.5rem;
          margin-bottom: 1.5rem;
          flex-wrap: wrap;

          .meta-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.9rem;
            color: #6b7280;

            svg {
              width: 16px;
              height: 16px;
            }

            &.date {
              font-weight: 500;
              color: #374151;
            }

            &.mood {
              padding: 0.25rem 0.75rem;
              border-radius: 15px;
              font-weight: 500;

              &.happy { background: rgba(34, 197, 94, 0.1); color: #16a34a; }
              &.excited { background: rgba(249, 115, 22, 0.1); color: #ea580c; }
              &.calm { background: rgba(59, 130, 246, 0.1); color: #2563eb; }
              &.thoughtful { background: rgba(139, 92, 246, 0.1); color: #7c3aed; }
              &.sad { background: rgba(156, 163, 175, 0.1); color: #6b7280; }
              &.tired { background: rgba(107, 114, 128, 0.1); color: #6b7280; }
              &.angry { background: rgba(239, 68, 68, 0.1); color: #dc2626; }

              .mood-emoji {
                margin-right: 0.25rem;
              }
            }
          }
        }

        .article-title {
          font-size: 2rem;
          font-weight: 700;
          color: #1e293b;
          line-height: 1.2;
          margin: 0;
        }
      }

      .article-body {
        .diary-content {
          font-size: 1.1rem;
          line-height: 1.8;
          color: #374151;
          margin-bottom: 2rem;

          ::v-deep(p) {
            margin-bottom: 1rem;
          }

          ::v-deep(br) {
            margin-bottom: 0.5rem;
          }
        }

        .diary-attachments {
          margin-bottom: 2rem;

          .attachments-title {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 1.1rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 1rem 0;

            svg {
              width: 18px;
              height: 18px;
              color: #6b7280;
            }
          }

          .photos-gallery {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1rem;

            .photo-item {
              position: relative;
              aspect-ratio: 1;
              border-radius: 8px;
              overflow: hidden;
              cursor: pointer;
              transition: all 0.3s ease;

              &:hover {
                transform: scale(1.02);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

                .photo-overlay {
                  opacity: 1;
                }
              }

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }

              .photo-overlay {
                position: absolute;
                inset: 0;
                background: rgba(0, 0, 0, 0.4);
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0;
                transition: opacity 0.3s ease;

                svg {
                  width: 24px;
                  height: 24px;
                  color: white;
                }
              }
            }
          }
        }

        .diary-tags {
          .tags-title {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 1.1rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 1rem 0;

            svg {
              width: 18px;
              height: 18px;
              color: #6b7280;
            }
          }

          .tags-container {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;

            .tag-item {
              padding: 0.25rem 0.75rem;
              background: rgba(59, 130, 246, 0.1);
              color: #2563eb;
              border: none;
              border-radius: 15px;
              font-size: 0.85rem;
              font-weight: 500;
              cursor: pointer;
              transition: all 0.2s ease;

              &:hover {
                background: rgba(59, 130, 246, 0.2);
                transform: translateY(-1px);
              }
            }
          }
        }
      }

      .article-footer {
        border-top: 1px solid #f1f5f9;
        padding-top: 1.5rem;
        margin-top: 2rem;

        .reading-info {
          display: flex;
          gap: 2rem;
          margin-bottom: 1.5rem;
          flex-wrap: wrap;

          .info-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.9rem;
            color: #6b7280;

            svg {
              width: 16px;
              height: 16px;
            }
          }
        }

        .article-actions {
          display: flex;
          gap: 1rem;

          .footer-action {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 0.9rem;
            font-weight: 500;

            svg {
              width: 16px;
              height: 16px;
            }

            &.like {
              color: #6b7280;

              &:hover {
                background: rgba(239, 68, 68, 0.1);
                border-color: #fecaca;
                color: #dc2626;
              }

              &.active {
                background: rgba(239, 68, 68, 0.1);
                border-color: #fecaca;
                color: #dc2626;
              }
            }

            &.bookmark {
              color: #6b7280;

              &:hover {
                background: rgba(59, 130, 246, 0.1);
                border-color: #bfdbfe;
                color: #2563eb;
              }

              &.active {
                background: rgba(59, 130, 246, 0.1);
                border-color: #bfdbfe;
                color: #2563eb;
              }
            }
          }
        }
      }
    }
  }

  .diary-sidebar {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;

    @media (max-width: 1024px) {
      margin-top: 2rem;
    }

    .navigation-card,
    .related-card,
    .mood-stats-card {
      background: white;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      padding: 1.5rem;

      .card-title {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 1.1rem;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 1rem 0;

        svg {
          width: 18px;
          height: 18px;
          color: #6b7280;
        }
      }
    }

    .navigation-card {
      .nav-links {
        display: flex;
        gap: 0.75rem;

        .nav-item {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 0.5rem;
          padding: 0.75rem;
          background: #f8fafc;
          color: #374151;
          text-decoration: none;
          border-radius: 8px;
          transition: all 0.2s ease;
          font-size: 0.9rem;
          font-weight: 500;

          &:hover:not(.disabled) {
            background: rgba(59, 130, 246, 0.1);
            color: #2563eb;
          }

          &.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
          }

          svg {
            width: 14px;
            height: 14px;
          }
        }
      }
    }

    .related-card {
      .related-list {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;

        .related-item {
          display: flex;
          align-items: center;
          gap: 1rem;
          padding: 0.75rem;
          border-radius: 8px;
          cursor: pointer;
          transition: background 0.2s ease;

          &:hover {
            background: #f8fafc;
          }

          .related-content {
            flex: 1;
            min-width: 0;

            .related-title {
              font-size: 0.9rem;
              font-weight: 500;
              color: #1e293b;
              margin: 0 0 0.25rem 0;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .related-meta {
              display: flex;
              gap: 0.75rem;
              font-size: 0.8rem;
              color: #6b7280;

              .related-mood {
                font-size: 1rem;
              }
            }
          }

          .related-arrow {
            width: 16px;
            height: 16px;
            color: #9ca3af;
          }
        }
      }
    }

    .mood-stats-card {
      .mood-chart {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;

        .mood-row {
          display: flex;
          align-items: center;
          gap: 0.75rem;

          .mood-info {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            min-width: 80px;

            .mood-emoji {
              font-size: 1.1rem;
            }

            .mood-label {
              font-size: 0.85rem;
              color: #374151;
              font-weight: 500;
            }
          }

          .mood-progress {
            flex: 1;
            height: 6px;
            background: #f1f5f9;
            border-radius: 3px;
            overflow: hidden;

            .mood-bar {
              height: 100%;
              border-radius: 3px;
              transition: width 0.3s ease;

              &.happy { background: #22c55e; }
              &.excited { background: #f97316; }
              &.calm { background: #3b82f6; }
              &.thoughtful { background: #8b5cf6; }
              &.sad { background: #9ca3af; }
              &.tired { background: #6b7280; }
              &.angry { background: #ef4444; }
            }
          }

          .mood-count {
            min-width: 24px;
            text-align: right;
            font-size: 0.85rem;
            color: #6b7280;
            font-weight: 500;
          }
        }
      }
    }
  }

  .comments-section {
    max-width: 1200px;
    margin: 2rem auto 0;
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .loading-state {
    max-width: 1200px;
    margin: 0 auto;
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    padding: 3rem 2rem;
    text-align: center;

    .loading-content {
      .loading-spinner {
        width: 40px;
        height: 40px;
        margin: 0 auto 1rem;
        border: 3px solid #f1f5f9;
        border-top: 3px solid #3b82f6;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }

      .loading-text {
        color: #6b7280;
        font-size: 1rem;
        margin: 0;
      }
    }
  }

  .photo-viewer-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    cursor: pointer;

    .photo-viewer {
      position: relative;
      max-width: 90vw;
      max-height: 90vh;
      cursor: default;

      .viewer-header {
        position: absolute;
        top: -60px;
        left: 0;
        right: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: white;
        z-index: 10;

        .viewer-info {
          display: flex;
          gap: 1rem;
          font-size: 0.9rem;

          .photo-counter {
            font-weight: 600;
          }

          .photo-name {
            opacity: 0.8;
          }
        }

        .viewer-close {
          width: 40px;
          height: 40px;
          background: rgba(255, 255, 255, 0.2);
          border: none;
          border-radius: 50%;
          color: white;
          cursor: pointer;
          transition: background 0.2s ease;

          &:hover {
            background: rgba(255, 255, 255, 0.3);
          }

          svg {
            width: 20px;
            height: 20px;
          }
        }
      }

      .viewer-content {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;

        .viewer-nav {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          width: 40px;
          height: 40px;
          background: rgba(255, 255, 255, 0.2);
          border: none;
          border-radius: 50%;
          color: white;
          cursor: pointer;
          transition: all 0.2s ease;

          &:hover:not(:disabled) {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-50%) scale(1.1);
          }

          &:disabled {
            opacity: 0.3;
            cursor: not-allowed;
          }

          &.prev {
            left: -60px;
          }

          &.next {
            right: -60px;
          }

          svg {
            width: 20px;
            height: 20px;
          }
        }

        .viewer-image {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain;
          border-radius: 8px;
        }
      }
    }
  }

  .modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2000;

    .modal-dialog {
      background: white;
      border-radius: 12px;
      min-width: 400px;
      max-width: 90vw;
      box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);

      .modal-header {
        padding: 1.5rem 1.5rem 1rem;
        border-bottom: 1px solid #f1f5f9;

        h3 {
          font-size: 1.1rem;
          font-weight: 600;
          color: #1e293b;
          margin: 0;
        }
      }

      .modal-body {
        padding: 1rem 1.5rem 1.5rem;

        p {
          color: #6b7280;
          margin: 0;
          line-height: 1.5;
        }
      }

      .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
        padding: 0 1.5rem 1.5rem;

        .modal-btn {
          padding: 0.5rem 1rem;
          border: none;
          border-radius: 6px;
          cursor: pointer;
          transition: all 0.2s ease;
          font-size: 0.9rem;
          font-weight: 500;

          &.secondary {
            background: #f3f4f6;
            color: #374151;

            &:hover {
              background: #e5e7eb;
            }
          }

          &.danger {
            background: #ef4444;
            color: white;

            &:hover {
              background: #dc2626;
            }
          }
        }
      }
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .diary-detail-view {
    padding: 1rem 0.5rem;

    .page-header .header-content {
      flex-direction: column;
      gap: 1rem;
      text-align: center;

      .header-left {
        justify-content: center;
      }

      .header-actions {
        justify-content: center;
        flex-wrap: wrap;
      }
    }

    .diary-article .article-container {
      padding: 1.5rem;

      .article-header .header-meta {
        justify-content: center;
        text-align: center;
      }

      .article-title {
        font-size: 1.5rem;
        text-align: center;
      }

      .diary-attachments .photos-gallery {
        grid-template-columns: 1fr;
      }

      .article-footer {
        .reading-info {
          justify-content: center;
          text-align: center;
        }

        .article-actions {
          justify-content: center;
        }
      }
    }

    .diary-sidebar {
      .navigation-card .nav-links {
        flex-direction: column;
      }
    }

    .photo-viewer-overlay .photo-viewer {
      .viewer-header {
        position: relative;
        top: 0;
        background: rgba(0, 0, 0, 0.8);
        padding: 1rem;
        border-radius: 8px 8px 0 0;
      }

      .viewer-content .viewer-nav {
        &.prev {
          left: 10px;
        }

        &.next {
          right: 10px;
        }
      }
    }
  }
}
</style>
